# -*- coding: utf-8 -*-
# @Time : 2022/6/20 11:33
# @Author : cheney
# @File : instruction.py
# @Software: PyCharm
# @Site: www.cheney.cc
"""
    指令类，用来表示不同类型的指令内容，接收用
"""
import datetime
import json
import time


class instruction:
    """ins_type表示指令的种类"""
    ins_type = -1
    direction = []  # 四个按钮的状态
    timestamp = -1  # 指令创建的时间戳，解析报文的时候直接用packet内的即可（主要是run内入栈使用）
    # duration = -1  # 指令执行时长
    speed = 50
    diff_speed = 20  # 转向时 两侧轮胎的差速
    sensor_list = []

    # todo:

    """ """
    CAR_MOVE = 0  # 控制小车运动
    CAR_STOP = 1  # 停止小车运动
    BACK_HOME = 2  # 返回出发点
    SENSOR_UP = 3  # 开启传感器
    SENSOR_DOWN = 4  # 关闭传感器
    ROUTER = 5  # 转发报文

    SIG_INIT_STOP = 6  # ctrl-c手动停止
    DISCONECT_STOP = 7  # 断开

    def __init__(self, ins_type: int, direction=None):
        if direction is None:
            self.direction = [False, False, False, False]
        else:
            self.direction = direction
        self.ins_type = ins_type
        if ins_type in [self.CAR_STOP, self.SIG_INIT_STOP, self.DISCONECT_STOP]:
            self.direction = [False, False, False, False]
            self.speed = 0
            self.diff_speed = 0

        self.set_time_current()

    def set_time_current(self):
        # self.timestamp = str(datetime.datetime.now())
        # self.timestamp = time.time()

        x = str(datetime.datetime.now())[11:].split(":")
        self.timestamp = float(x[0])*60*60 + float(x[1])*60 + float(x[2])

    def from_json(self, data_json: json, encoding: str = 'utf-8'):
        """
        从json中解析字段到对象
        :param data_json:
        :param encoding:
        :return:
        """
        try:
            if self.ins_type == self.CAR_MOVE:
                self.direction = data_json["direction"]
                self.speed = data_json["speed"]
                self.diff_speed = data_json["diff_speed"]
            elif self.ins_type in [self.SENSOR_UP, self.SENSOR_DOWN]:
                self.sensor_list = data_json["sensor_list"]
        except KeyError:
            print("no such key ")
        # todo:完善

    def to_json(self) -> json:
        """
        返回指令栈的时候使用
        :return:
        """
        ans = {
            "direction": self.direction,
            "timestamp": self.timestamp,
            "speed": self.speed,
            "diff_speed": self.diff_speed,
            "sensor_list": self.sensor_list
        }
        # todo

        return json.dumps(ans)

    def to_string(self) -> str:
        """
        返回指令栈的时候使用
        :return:
        """
        pass

